package com.liao.ten.utils;

import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.liao.ten.moive.MovieDetailInfo;

import org.json.JSONArray;
import org.litepal.LitePal;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class FileUtil {

    public static void saveDataToFile(Context context, String fileName, String data) {
        try {
            FileOutputStream os = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            os.write(data.getBytes());
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDataToFile(Context context, String fileName) {
        String msg = null;
        try {
            FileInputStream fis = context.openFileInput(fileName);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            fis.close();
            msg = bos.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg;
    }

    public static void saveDataToDB(String data) {
        LitePal.getDatabase();
        MovieDetailInfo movieDetailInfo = new Gson().fromJson(data, MovieDetailInfo.class);
        movieDetailInfo.save();
    }

    public static String getDataToDB(String idName, String table, Class c, int id) {
        LitePal.getDatabase();
        String sql = "select id from " + table + " where " + idName + "=" + id;
        Cursor cursor = LitePal.findBySQL(sql);
        Object first = LitePal.where(idName + "=?", String.valueOf(id)).findFirst(c);
        System.out.println("FileUtil.getDataToDB=================" + first.toString());
//        int index = cursor.getColumnIndex("_id");
//        int author = cursor.getColumnIndexOrThrow("_author");
//        System.out.println("FileUtil.getDataToDB=====================" + id);
//        System.out.println("FileUtil.getDataToDB=====================" + index);
//        int anInt = cursor.getInt(index);
//        Object o = LitePal.find(c, anInt);
        String s = new Gson().toJson(first);
//        s = s.substring(1, s.length() - 1).trim();
        return s;
    }
}
